package com.dommettj.rawfix.settings;

import org.apache.log4j.Logger;

import java.io.File;
import java.net.URL;

public class FileProviderImpl implements FileProvider {

    private static final Logger logger = Logger.getLogger(FileProviderImpl.class);

    @Override
    public File getFileForReading(final String filename) {

        final File userFile = getUserFile(filename);

        if(userFile.exists()) {
            return userFile;
        } else {
            try {
                return getDefaultFile(filename);
            } catch (Exception e) {
                logger.error("Failed to load default file [" + filename + "], returning empty user file");
                return userFile;
            }
        }
    }

    @Override
    public File getFileForWriting(final String filename) {

        return getUserFile(filename);
    }

    private File getUserFile(final String filename) {

        final String filePath = System.getProperty("user.home") + File.separator + filename;
        return new File(filePath);
    }

    private File getDefaultFile(final String filename) throws Exception {

        final URL url = getClass().getClassLoader().getResource(filename);

        if(url != null) {
            return new File(url.toURI().getPath());
        } else {
            throw new Exception("Could not find default file");
        }
    }
}
